app.py
設置好API後,要讓Html呼叫,取得資料後繪圖。
首先宣告Html的元素
<div class="row">
<div id="habit_stat" style="width:50%; height:400px;" class="col"></div>
<div id="habit_stat_2" style="width:50%; height:400px;" class="col"></div>
</div>
宣告將要繪圖的位置
接著寫AJAX的function
function get_habit(){
let p = $("#player").val();
let habit_stat = echarts.init(document.getElementById('habit_stat'), 'white', { renderer: 'canvas' });
let habit_stat_2 = echarts.init(document.getElementById('habit_stat_2'), 'white', { renderer: 'canvas' });
if(p!=='選擇球員'){
$.ajax({
type: 'POST',
url: '/gethabit',
data: {'p':p},
success: function(result){
console.log(result);
let option = {
title: {
text: result['name']
},
legend: {
data: ['AVG', 'SLG', 'OBP']
},
toolbox: {
show: true,
orient: 'vertical',
left: 'right',
top: 'center',
},
tooltip: {
trigger: 'axis'
},
xAxis: {
data: ['vsRHP', 'vsLHP']
},
yAxis: {},
series: [{
name: 'AVG',
type: 'bar',
data: [result['vsRHP']['AVG'], result['vsLHP']['AVG']]
}, {
name: 'OBP',
type: 'bar',
data: [result['vsRHP']['OBP'], result['vsLHP']['OBP']]
}, {
name: 'SLG',
type: 'bar',
data: [result['vsRHP']['SLG'], result['vsLHP']['SLG']]
}]
};
habit_stat.clear();
habit_stat.setOption(option, true);
let option2 = {
legend: {},
tooltip: {
trigger: 'axis'
},
dataset: {
dimensions: ['stat', 'PA', 'AB', 'RBI', 'H', 'HR'],
source: [
{ stat: 'vsRHP', 'PA': result['vsRHP']['PA'], 'AB': result['vsRHP']['AB'], 'RBI': result['vsRHP']['RBI'], 'H': result['vsRHP']['H'], 'HR': result['vsRHP']['HR'] },
{ stat: 'vsLHP', 'PA': result['vsLHP']['PA'], 'AB': result['vsLHP']['AB'], 'RBI': result['vsLHP']['RBI'], 'H': result['vsLHP']['H'], 'HR': result['vsLHP']['HR'] },
]
},
xAxis: { type: 'category' },
yAxis: {},
series: [
{ type: 'bar' },
{ type: 'bar' },
{ type: 'bar' },
{ type: 'bar' },
{ type: 'bar' }
]
};
habit_stat_2.clear();
habit_stat_2.setOption(option2, true);
}
});
}
}
這邊用了不太一樣的寫法,但結果差不多
成果
電腦出問題,這篇內容有點少,但網站已經上heroku了(連結),下一篇講git